//
//  JDPlayVideoOrPictureViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/7/25.
//

import UIKit
import AVKit
import AVFoundation

enum JDPlayType {
    case video
    case picture
    case empty
}

class VideoPlayer: UIView {
    override class var layerClass: AnyClass {
        get {
            return AVPlayerLayer.self
        }
    }
}

/// 播放视频 或者 图片
class JDPlayVideoOrPictureViewController: UIViewController {

    var mainCollectionView: UICollectionView?
    var picDataSource: [String]?
    var videoDataSource: [String]?
    var playType: JDPlayType = .empty
    
    private var avplayer: AVPlayer!
//    private var videoView: VideoPlayer! // 显示的视频
//    private var playerItem: AVPlayerItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        self.view.frame = .zero
//        self.picDataSource = ["https://ww1.sinaimg.cn/mw690/5e234aealy1hrtjpz1bk3j20zm1hcars.jpg", "https://img1.baidu.com/it/u=1990142713,995124316&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500"]
//        self.videoDataSource = [""]
        self.setupUIElements()
        // Do any additional setup after loading the view.
    }

    func setupUIElements() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        
        self.mainCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        self.mainCollectionView?.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(self.mainCollectionView!)
        NSLayoutConstraint.activate([
            self.mainCollectionView!.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.mainCollectionView!.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            self.mainCollectionView!.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.mainCollectionView!.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        
        self.mainCollectionView?.delegate = self
        self.mainCollectionView?.dataSource = self
        self.mainCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
//        DispatchQueue.main.asyncAfter(deadline: .now()+0.5) { [weak self] in
//            self?.mainCollectionView?.reloadData()
//        }
        let backButton = UIButton(type: .custom)
        self.view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalTo(self.view)
            make.top.equalTo(self.view).offset(UIDevice().safeAreaInset.top-44)
            make.size.equalTo(CGSizeMake(44, 44))
        }
        backButton.setImage(UIImage(named: "black_back")?.withRenderingMode(.alwaysOriginal), for: .normal)
        backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
    }
    
}

extension JDPlayVideoOrPictureViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        printLog("这个地方调用了几次")
        if self.playType == .picture {
            printLog("这个地方调用了几次666")
            return self.picDataSource?.count ?? 0
        } else if self.playType == .video{
            printLog("这个地方调用了几次888")
            return self.videoDataSource?.count ?? 0
        } else {
            printLog("这个地方调用了几次999")
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }
        
        var currentUrlStr = ""
        
        if self.playType == .video {
            currentUrlStr = self.videoDataSource?.first ?? ""
            cell.contentView.backgroundColor = .commonColor()
            // 视频
            if let videoURL = URL(string: currentUrlStr) {
                self.avplayer = AVPlayer(url: videoURL)
                let playerLayer = AVPlayerLayer(player: self.avplayer!)
                playerLayer.frame = CGRectMake(0, 0, screenWidth, screenHeight)
                cell.contentView.layer.addSublayer(playerLayer)
                DispatchQueue.main.asyncAfter(deadline: .now()+1) { [weak self] in
                    self?.avplayer.play()
                    printLog("播放视频")
                }
            }
        } else if self.playType == .picture {
            // 图片
            currentUrlStr = self.picDataSource?[indexPath.row] ?? ""
            let imgV = UIImageView()
            cell.contentView.addSubview(imgV)
            imgV.frame = CGRectMake(0, 0, screenWidth, screenHeight)
            imgV.contentMode = .scaleAspectFit
//            self.imgVOne?.kf.setImage(with: URL(string: JDImageBaseUrl + (confirmModel.picurl1 ?? "")))
            
            if currentUrlStr.hasPrefix("http")  {
                imgV.kf.setImage(with: URL(string: currentUrlStr), placeholder: nil, options: nil) { result in

                }
            } else {
                imgV.downloadImage(currentUrlStr)
            }
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: screenWidth, height: screenHeight)
    }
    
    @objc func backAction() {
        self.view.removeFromSuperview()
        self.avplayer.pause()
    }
    
}

//extension JDPlayVideoOrPictureViewController {
//
//    func showAnimate() {
//        UIView.animate(withDuration: 0.5) {
//
//        }
//    }
//
//    func hideAnimate() {
//
//    }
//}
